/*
 * Copyright 2009 by Konstantin Bulenkov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bulenkov.crawler.util;

import com.bulenkov.crawler.CrawlerJob;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Konstantin Bulenkov
 */
public class Downloader {
  private static final int BUF_SIZE = 8192;
  private static final Map<ThreadGroup, Long> DOWNLOAD_INFO = new HashMap<ThreadGroup, Long>();

  public static Page download(String uri) {
    try {
      final HttpMethod method = new GetMethod(uri);
      method.setFollowRedirects(true);
      final int code = new HttpClient().executeMethod(method);
      if (code != -1) {
        InputStream is = method.getResponseBodyAsStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] bytes = new byte[BUF_SIZE];
        StringBuilder sb = new StringBuilder();
        int count = bis.read( bytes );
        while( count != -1 && count <= BUF_SIZE) {
         sb.append(new String(bytes, 0, count));
         count = bis.read( bytes );
        }
        bis.close();
        method.releaseConnection();
        saveDownloadInfo(Thread.currentThread().getThreadGroup(), sb.length());
        return new Page(code, sb.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  private static void saveDownloadInfo(ThreadGroup threadGroup, int size) {
    if (threadGroup == null) return;

    Long newsize = DOWNLOAD_INFO.get(threadGroup);

    if (newsize == null) newsize = 0L;

    newsize += size;
    DOWNLOAD_INFO.put(threadGroup, newsize);
  }

  public static long getDownloadedSize(CrawlerJob job) {
    final Long size = DOWNLOAD_INFO.get(job.getThreadGroup());
    return size == null ? 0 : size;
  }
}
